package cn.edu.seu.ssny.controller;

import cn.edu.seu.ssny.common.Constants;
import cn.edu.seu.ssny.common.DateEditor;
import cn.edu.seu.ssny.enums.ResultCodeEnum;
import cn.edu.seu.ssny.common.utils.DateUtils;
import cn.edu.seu.ssny.entity.Project;
import cn.edu.seu.ssny.exception.SsnyException;
import cn.edu.seu.ssny.service.IUserService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class BaseController {
    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    @Autowired
    private IUserService userService;

    @InitBinder
    protected void initBinder(WebDataBinder webDataBinder) {
        webDataBinder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        webDataBinder.registerCustomEditor(Date.class, new DateEditor(true));
    }

    /**
     * 带参重定向
     *
     * @param path
     * @return
     */
    protected String redirect(String path) {
        return "redirect:" + path;
    }

    /**
     * 不带参重定向
     *
     * @param response
     * @param path
     * @return
     */
    protected String redirect(HttpServletResponse response, String path) {
        try {
            response.sendRedirect(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取分页请求
     *
     * @return
     */
    protected PageRequest getPageRequest() {
        int page = 1;
        int size = 10;
        Sort sort = null;
        try {
            String sortName = request.getParameter("sortName");
            String sortOrder = request.getParameter("sortOrder");
            if (StringUtils.isNoneBlank(sortName) && StringUtils.isNoneBlank(sortOrder)) {
                if (sortOrder.equalsIgnoreCase("desc")) {
                    sort = new Sort(Direction.DESC, sortName);
                } else {
                    sort = new Sort(Direction.ASC, sortName);
                }
            }
            page = Integer.parseInt(request.getParameter("pageNumber")) - 1;
            size = Integer.parseInt(request.getParameter("pageSize"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        PageRequest pageRequest = new PageRequest(page, size, sort);
        return pageRequest;
    }

    /**
     * 获取分页请求
     *
     * @param sort 排序条件
     * @return
     */
    protected PageRequest getPageRequest(Sort sort) {
        int page = 0;
        int size = 10;
        try {
            String sortName = request.getParameter("sortName");
            String sortOrder = request.getParameter("sortOrder");
            if (StringUtils.isNoneBlank(sortName) && StringUtils.isNoneBlank(sortOrder)) {
                if (sortOrder.equalsIgnoreCase("desc")) {
                    sort.and(new Sort(Direction.DESC, sortName));
                } else {
                    sort.and(new Sort(Direction.ASC, sortName));
                }
            }
            page = Integer.parseInt(request.getParameter("pageNumber")) - 1;
            size = Integer.parseInt(request.getParameter("pageSize"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        PageRequest pageRequest = new PageRequest(page, size, sort);
        return pageRequest;
    }

    public static JSONObject getRequestJsonObject(HttpServletRequest request) throws IOException {
        String json = getRequestJsonString(request);
        return JSONObject.parseObject(json);
    }

    /***
     * 获取 request 中 json 字符串的内容
     *
     * @param request
     * @return : <code>byte[]</code>
     * @throws IOException
     */
    public static String getRequestJsonString(HttpServletRequest request)
            throws IOException {
        String submitMehtod = request.getMethod();
        // GET
        if (submitMehtod.equals("GET")) {
            return new String(request.getQueryString().getBytes("iso-8859-1"), "utf-8").replaceAll("%22", "\"");
            // POST
        } else {
            return getRequestPostStr(request);
        }
    }

    /**
     * 描述:获取 post 请求的 byte[] 数组
     * <pre>
     * 举例：
     * </pre>
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if (contentLength < 0) {
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength; ) {

            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }

    /**
     * 描述:获取 post 请求内容
     * <pre>
     * 举例：
     * </pre>
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }

    /**
     * 功能描述:
     * <返回当前项目
     *
     * @param session
     * @return
     */
    public Project getCurrProject(HttpSession session) {
        Project project = (Project) session.getAttribute(Constants.CURRENT_PROJECT);
        if (project == null) {
            throw new SsnyException(ResultCodeEnum.ERROR_NOPROJECT_CHOOSE);
        }
        return project;
    }

    /**
     * 功能描述:
     * <将时间列表转化为字符串列表
     *
     * @param dateList
     * @return
     */
    public List<String> transDateListToDateString(List<Date> dateList) {
        List<String> dates = new ArrayList<>();
        dateList.stream().forEach(date -> {
            dates.add(DateUtils.format(date, DateUtils.ssnyPattern));
        });
        return dates;
    }

    public void checkTimeMode(int timeMode) {
        if (timeMode != DateUtils.MODE_HOUR && timeMode != DateUtils.MODE_DAY && timeMode != DateUtils.MODE_MONTH && timeMode != DateUtils.MODE_YEAR) {
            throw new SsnyException(ResultCodeEnum.ERROR_TIMEMODE);
        }
    }


}
